import { ADD_TODO, DEL_TODO, SELECT_ALL, UPDATE_TODO } from '../types'

// 该函数是用来获取当前选中的数量和是否为全选
function selectCountFn (list) {

  // 过滤出被选中的内容
  const arr = list.filter(item => item.is)
  return {
    // 选中的数量
    selectCount: arr.length,
    // 是否全选
    isAll: arr.length === list.length
  }
}

const reducer = (state = {
  selectCount: 1, // 定义全局已经选中的数量
  isAll: false, // 标记是否为全选
  todoList: [
    {
      is: false,
      title: '美美的睡上一觉',
      id: 'abcdsldkjflskjdgipweiof'
    }, {
      is: true,
      title: '认真的听会课',
      id: 'qwerlsjfisodhfskdfhoisho'
    }, {
      is: false,
      title: '下课休息一会',
      id: 'ksfjglkshgoisfjsofjoshfsofd'
    },
  ]
}, action) => {

  let obj = null

  switch (action.type) {
    case ADD_TODO:

      // 将内容加到原数组中
      state.todoList.push(action.payload)
      // 将数组传递到方法中获取选中的数量
      obj = selectCountFn(state.todoList)
      // 将最终的结果返回
      return { ...state, todoList: [...state.todoList], ...obj }
    case DEL_TODO:

      // 找到要删除元素的索引值
      const index = state.todoList.findIndex(item => item.id === action.payload.id)
      state.todoList.splice(index, 1)

      // 将数组传递到方法中获取选中的数量
      obj = selectCountFn(state.todoList)
      return { ...state, todoList: [...state.todoList], ...obj }

    case UPDATE_TODO:
      // 1. 找到要更新元素的索引值
      const index2 = state.todoList.findIndex(item => item.id === action.payload.id)
      // 2. 修改元素
      state.todoList.splice(index2, 1, action.payload)

      // 将数组传递到方法中获取选中的数量
      obj = selectCountFn(state.todoList)

      // 3. 返回结果
      return { ...state, todoList: [...state.todoList], ...obj }
    case SELECT_ALL:

      state.todoList.forEach(item => {
        item.is = action.payload
      })
      // 将数组传递到方法中获取选中的数量
      obj = selectCountFn(state.todoList)
      return { ...state, todoList: [...state.todoList], ...obj }
    default:
      return { ...state }
  }
}
export default reducer
